/**
 * Copyright (c) 2012 Tomi Paananen.
 *
 * Part of Quick Gestures user interface.
 */

import QtQuick 1.1
import com.nokia.symbian 1.1
import QuickGestures 1.0

Page {
    id: editorPage

    property GestureModel model: null
    property int gestureId: -1
    property bool gestureIsFromList: false
    property bool modified: false
    property bool doCenter: false

    // Gesture object for editing.
    Gesture {
        id: editorGesture
        gestureId: Math.random() * 32000;
        name: "Untitled"
    }

    onGestureIdChanged: {
        console.debug("EditorPage.qml: onGestureIdChanged:", gestureId);

        if (gestureId >= 0) {
            // Try to locate the gesture from the model.
            if (model && helper.copy(model.gestureById(gestureId), editorGesture)) {
                doCenter = true;
                gestureIsFromList = true;
                emptyPageInfo.visible = false;
            }
            else {
                if (!model) {
                    console.debug("EditorPage.qml: onGestureIdChanged: Error: "
                                  + "No model set! Make sure the model is set "
                                  + "before the ID.");
                }

                console.debug("EditorPage.qml: onGestureIdChanged: Failed to "
                              + "copy the gesture data!");
            }
        }
        else {
            clearGesture();
        }

        updateControls();
    }

    onWidthChanged: {
        if (doCenter) {
            centerGesture();
        }
    }
    onHeightChanged: {
        if (doCenter) {
            centerGesture();
        }
    }

    Connections {
        target: root
        onInPortraitChanged: doCenter = true;
    }

    /**
     * Centers the gesture.
     */
    function centerGesture()
    {
        if (editorPage.width > 0 && editorPage.height > 0) {
            helper.center(editorGesture, editorPage.width,
                          editorPage.height - editorControls.height / 3);
            doCenter = false;
        }
        else {
            console.debug("EditorPage.qml: centerGesture(): Will not center",
                          "because the width or the height of the page is zero!");
        }
    }

    /**
     * Clears the editor gesture.
     */
    function clearGesture()
    {
        editorGesture.clear();
        editorGesture.gestureId = Math.random() * 32000;
        editorGesture.name = "Untitled"
        gestureIsFromList = false;
        emptyPageInfo.visible = true;
    }

    /**
     * Updates the controls according to the attributes of editorGesture.
     */
    function updateControls()
    {
        editorControls.fixedStartingPoint =
                (editorGesture.attributes & Gesture.FixedStartingPoint);
        editorControls.fixedDirection =
                (editorGesture.attributes & Gesture.FixedDirection);
    }

    /**
     * Saves the changes.
     */
    function save()
    {
        console.debug("EditorPage.qml: save()");
        helper.autoProcess = true;

        if (!modified) {
            console.debug("EditorPage.qml: save():",
                          "The current gesture has not been modified!");
            return;
        }

        if (gestureIsFromList) {
            if (!helper.update(editorGesture, model)) {
                console.debug("EditorPage.qml: save():",
                              "Failed to update the changes!");
                return;
            }

            centerGesture();
        }
        else {
            // Add the new gesture to the model.
            if (!helper.copyAndAppend(editorGesture, model)) {
                console.debug("EditorPage.qml: save():",
                              "Failed to append a new gesture!");
                return;
            }

            gestureIsFromList = true;
        }

        helper.setModified(editorGesture.gestureId);
        modified = false;
    }

    ViewHeader {
        id: viewHeader
        width: parent.width
        text: editorGesture.gestureId + "; " + editorGesture.name;
        elide: Text.ElideRight
        visible: root.inPortrait
    }

    EmptyPageInfo {
        id: emptyPageInfo
        text: "Sketch a gesture here"
    }

    // The controls for the gesture settings.
    EditorControls {
        id: editorControls
        property bool maximized: false
        state: "Minimized"
        y: parent.height - editorControls.height / 3
        z: 2

        anchors {
            left: parent.left
            right: parent.right
        }

        gestureId: editorGesture.gestureId
        name: editorGesture.name
        fixedStartingPoint: (editorGesture.attributes & Gesture.FixedStartingPoint)
        fixedDirection: (editorGesture.attributes & Gesture.FixedDirection)

        onFixedStartingPointSet: {
            if (set) {
                editorGesture.attributes =
                        Gesture.FixedStartingPoint
                        | Gesture.FixedDirection;
                fixedDirection = true;
            }
            else {
                editorGesture.attributes =
                        (editorGesture.attributes
                         & ~Gesture.FixedStartingPoint);
            }

            console.debug("editorGesture.attributes ==",
                          editorGesture.attributes);
            editorPage.modified = true;
        }

        onFixedDirectionSet: {
            if (set) {
                editorGesture.attributes |= Gesture.FixedDirection;
            }
            else {
                editorGesture.attributes =
                        (editorGesture.attributes
                         & ~Gesture.FixedDirection);
            }

            console.debug("editorGesture.attributes ==",
                          editorGesture.attributes);
            editorPage.modified = true;
        }

        states: [
            State {
                name: "Minimized"

                PropertyChanges {
                    target: editorControls
                    y: parent.height - editorControls.height / 3
                }
            },
            State {
                name: "Maximized"

                PropertyChanges {
                    target: editorControls
                    y: parent.height - editorControls.height
                }
            }
        ]
        transitions: [
            Transition {
                from: "*"; to: "*";

                NumberAnimation {
                    properties: "y"
                    duration: 200
                    easing.type: Easing.InOutQuad
                }
            }
        ]
    }

    // Visualizer for painting the editor gesture.
    GestureVisualizer {
        id: gestureVisualizer

        anchors {
            top: viewHeader.visible ? viewHeader.bottom : parent.top;
            left: parent.left
            right: parent.right
            bottom: parent.bottom
        }

        autoScale: false

        Component.onCompleted: {
            editorGesture.clear();
            gesture = editorGesture;
        }
    }

    // Mouse area for sketching the gesture.
    MouseArea {
        id: editorPageMouseArea

        anchors {
            top: viewHeader.visible ? viewHeader.bottom : parent.top;
            left: parent.left
            right: parent.right
            bottom: parent.bottom
        }

        z: 1

        onPressed: {
            console.debug("EditorPage.qml: Locking the orientation.");
            editorPage.orientationLock = PageOrientation.LockPrevious;

            if (editorGesture.pointCount) {
                // Add a break point.
                editorGesture.appendPoint(-1, -1);
            }
            else {
                // Hide the empty page info.
                emptyPageInfo.visible = false;
            }

            editorGesture.appendPoint(mouse.x, mouse.y);

            if (!editorPage.modified) {
                editorPage.modified = true;
            }
        }
        onMousePositionChanged: {
            editorGesture.appendPoint(mouse.x, mouse.y);
        }
        onReleased: {
            console.debug("EditorPage.qml: Releasing the orientation lock.");
            editorPage.orientationLock = PageOrientation.Automatic;
        }
    }

    tools: ToolBarLayout {
        ToolButton {
            iconSource: "toolbar-back"
            onClicked: pageStack.pop();
        }
        ToolButton {
            iconSource: "qrc:/save-icon.png"
            onClicked: save();
        }
        ToolButton {
            iconSource: "toolbar-delete"
            onClicked: clearGesture();
        }
        ToolButton {
            iconSource: "toolbar-settings"
            checkable: true

            onCheckedChanged: {
                if (checked) {
                    editorControls.state = "Maximized";
                }
                else {
                    editorControls.state = "Minimized";
                }
            }
        }
    }
}
